package cn.kgc.controller;


import cn.kgc.config.WechatConfig;
import cn.kgc.dto.Result;
import cn.kgc.service.UsersService;
import cn.kgc.utils.redis.ResultUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author qf
 * @since 2022-03-03
 */
@RestController
@RequestMapping("/api/user")
public class UsersController {

    private final WechatConfig wechatConfig;
    private final UsersService usersService;
    public UsersController(WechatConfig wechatConfig, UsersService usersService) {
        this.wechatConfig = wechatConfig;
        this.usersService = usersService;
    }

    @GetMapping("/login/wechat")
    public void wxLogin(HttpServletResponse response) throws IOException {

        String url = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=%s&" +
                "redirect_uri=%s&" +
                "response_type=code&" +
                "scope=snsapi_login&" +
                "state=STATE#wechat_redirect";
        response.sendRedirect(String.format(url, wechatConfig.getAppid(), wechatConfig.getRedirect_uri()));
    }

    @GetMapping ("/info")
    public Result getInfo(HttpServletRequest request){
        String token=request.getHeader ("token");
        Map<String,Object> info= usersService.getInfo(token);
        Result result= ResultUtils.returnDataSuccess (info);
        return result;
    }

    @PostMapping("/login/sms")
    public Result<Map<String,String>> loginSms(String phone,String sms){
        String token = usersService.loginSms (phone, sms);
        Map<String,String> map=new HashMap<>();
        map.put ("token",token);
        return ResultUtils.returnDataSuccess (map);
    }
}
